﻿using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace ShanNiang.Hosting.Extensions
{
    /// <summary>
    /// json扩展类
    /// </summary>
    public static class JsonExtension
    {
        /// <summary>
        /// 将当前对象转换为 Json字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="opt">序列化设置</param>
        /// <returns></returns>
        public static string? ToJson(this object obj, Action<JsonSerializerSettings>? opt = null)
        {
            if (obj == null)
                return null;

            JsonSerializerSettings settings = new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore,
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            if (opt != null)
            {
                opt.Invoke(settings);
            }

            return JsonConvert.SerializeObject(obj, settings);
        }
        public static T? FromJson<T>(this string json, Action<JsonSerializerSettings>? opt = null)
        {
            if (json == null)
                return default(T);
            if (json.Trim() == string.Empty)
                return default(T);
            JsonSerializerSettings settings = new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore,
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            if (opt != null)
            {
                opt.Invoke(settings);
            }
            return JsonConvert.DeserializeObject<T>(json, settings);
        }

        public static object? FromJson(this string json, Type targetType, Action<JsonSerializerSettings>? opt = null)
        {
            if (json == null)
                return Activator.CreateInstance(targetType);
            if (json.Trim() == string.Empty)
                return Activator.CreateInstance(targetType);
            JsonSerializerSettings settings = new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore,
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            if (opt != null)
            {
                opt.Invoke(settings);
            }
            return JsonConvert.DeserializeObject(json, targetType, settings);
        }
    }
}
